/******************************************************************************
 * (c) Arphen Lin, arphenlin@gmail.com
 * 2007/08/27
 ******************************************************************************/

/*******************************************************************************
 * Wait for required javascripts
 ******************************************************************************/
var showConsole = false;	// console window
var timer = setInterval('timeout()', 100);

function timeout(){
	if(GMLib && Prototype){
		clearInterval(timer);
		if(showConsole) gmConsole.init();	
		main();
	}
}

/*******************************************************************************
 * Write your code here
 ******************************************************************************/
function main(){
	function extendUrlParams(){
		var url = THIS_URL;

		// leagueId
		var i = url.indexOf('/b1/');
		if(i>0){
			var lid = url.substring(i+4, url.length);
			i = lid.indexOf('/');
			if(i<0) i=lid.indexOf('?');
			lid = lid.substring(0, i>0? i : lid.length);
			//urlObj.params.push(['leagueId', lid]);
			THIS_URL_PARAMS['leagueId'] = lid;
			_log('leagueId='+lid);

			// team id
			var teamId = 0;
			i = url.indexOf('/'+lid+'/');
			if(i>0){
				var j = url.indexOf('?');
				if(j<0){
					teamId = parseInt(url.substring(i+lid.length+2, url.length));
				}else{
					teamId = parseInt(url.substring(i+lid.length+2, j));
				}
				//urlObj.params.push(['teamId', teamId]);
				THIS_URL_PARAMS['teamId'] = teamId;
				_log('teamId='+teamId);
			}
		}
	}

	// =====================================================================================================
	extendUrlParams();

	const LEAGUE_ID = THIS_URL_PARAMS.leagueId;
	const TEAM_ID = THIS_URL_PARAMS.teamId;

	const ICON_MAN_GREEN = 'data:image/gif;base64,'+
	'R0lGODlhCQAKANUAAP///+D/2M74x7T9pLT6uMX0wMfxw7/0tMvnx6rwpZz3jIvvd4XpdY3mfJfi'+
	'hYnhd4zee3ziapXViZnMmXrYZnLPY4XEeWjHVGO9V2itW1iZPUyZMVaSMUGZMkCWOTyULD2LMkmF'+
	'NjmJLDaGKjCDIy+DHEF6IzZ7LSl9ISZ7GSR5ESFzFihtIBtwERhrEBBjB////wAAAAAAAAAAAAAA'+
	'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAUUADAALAAAAAAJAAoAAAZDQJhQ'+
	'A9oIjyYLLJE6wkySwKDpVF0+Tlio1CFxjhlEwVCYsGAoh+CwJmBOqUWD8qAwIq5UxaPokyAuMC0u'+
	'IiMiLyswQQA7';

	const ICON_ESPN = 'data:image/gif;base64,'+
	'R0lGODlhDwAPAOYAAPT29Ozu7Ozq7PTi5OTi5PTW1NTW1NTS1NTOzPTCvPTCxMzKzNTGxMTCxLy+'+
	'vPSurLy6vOSurOyqrNyurMyytLS2tNyqrLSytLSurKyurOyWlLyipKyipOyGhKSWlOSChKySlOx+'+
	'fKSOjNx6fKSKhPRydJyGhMR6dOxqZOxWVMReXORSVOxOTJRaXLxOTIxaXJRWVNxCPKROTNw+PNQ+'+
	'POw2NOQ2NOwuLHxGRMQyLNwmJOwiHOQiHNQmJHQ+PNQiJNQiHMwiHNQeHMweHNQaFMQeHMwaFIQq'+
	'LMQaFHQuLHwqJMQWFIQmJLwWFLQWFHQmJIweHLQSFLQSDIQeHKwSFIwaHKwSDKQSFJQWFIQaFJQS'+
	'FHwWFJQODIQSFIwKDHwODHQODGwKBP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+
	'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5'+
	'BAUUAGIALAAAAAAPAA8AAAezgGISKTE0M4eIMzkwYmIdNUFDkpNDQlc+DWIoRFJRnp9RUl44mSpY'+
	'XaipqVsvC2IDGyCys7MiHAZiChETEb2+ERYUAmIFLDY/PzrKy0VPCGIJN0NITVFUoFxJGGIPO9Rc'+
	'U0fi4kwtEGIaPEhRYCYXEPDwFQdiITxLTloyIx/9HycMGpW412TJkB4IdQD5QmLYCiOgQFkJY4KA'+
	'GBdVoGiswpFjFiUeAjRykOGCyZMnIQAQEwgAOw==';

	const ICON_REFRESH = 'data:image/gif;base64,'+
	'R0lGODlhDAAMALMAAP//AP/vAP+/AP+vAP+fAP+PAP9gYP8vAP8QEP8AAP///wAAAAAAAAAAAAAA'+
	'AAAAACH5BAUUAAoALAAAAAAMAAwAAAQ3UEmDUkJG6jqEKNdmHQEAEKFhjeWZUCtrEohg3vhp5zgd'+
	'J6QZJhZ0ZSrAFgoh6nxCGgXskpFEAAA7';

	const ICON_STAR_RED = 'data:image/gif;base64,'+
	'R0lGODlhCQAJAOMAAPz+/PxaPPxmTPyGZPwOBPwKBPyObPwiDPxKBPwGBPweBPwCBPQC'+
	'BPzWBAAAAICAgCH5BAEAAAAALAAAAAAJAAkAAAQwEEgRggTCgEIIGAKzIAqCJMgBLEvj'+
	'shLrNvDavgtwnGS5MIIBgFAoAAyCS0CQlEQAADs=';


	const URL_YFB = 'http://baseball.fantasysports.yahoo.com/b1/'+LEAGUE_ID;
	const YFB = {
		URL_PLAYER_SEARCH: URL_YFB+'/playersearch?search=<playerName>',
		URL_PLAYER_SEARCH_2006: URL_YFB+'/playersearch?stat1=S_S_2006&search=<playerName>',
		URL_PITCHER_TOTAL: URL_YFB+'/players?status=A&pos=P&cut_type=33&stat1=S_S_2007&sort=AR',
		URL_BATTER_TOTAL: URL_YFB+'/players?status=A&pos=B&cut_type=33&stat1=S_S_2007&sort=AR',
		URL_BATTER_TOTAL_TEAM: URL_YFB+'/players?status=<teamId>&pos=B&cut_type=33&stat1=S_S_2007&sort=AR',
		URL_WATCH_TOTAL: URL_YFB+'/'+TEAM_ID+'/playerswatch?&stat1=S&stat2=S_2007&sort=AR',
		URL_STANDINGS: URL_YFB+'/standings',
		URL_PLAYER_GAMELOG: 'http://sports.yahoo.com/mlb/players/<playerId>/gamelog',
		URL_ESPN_PLAYER_PICTURE: 'http://assets.espn.go.com/i/mlb/profiles/players/65x90/<playerId>.jpg'
	};

	const STATS_DAILY = { // low, high
	  RANK:	[100, 200],
		R: 		[1, 2],
		H: 		[1, 3],
		HR: 	[1, 1],
		RBI: 	[1, 2],
		SB: 	[1, 1],
		FPCT: [0.97, 0.99],
		AVG: 	[0.3, 0.5],
		OBP: 	[0.5, 0.6],
		SLG: 	[0.45, 0.53],
		W: 		[1, 1],
		SV: 	[1, 1],
		HLD: 	[1, 1],
		K: 		[4, 6],
		GIDP:	[1, 2],
		ERA_SP:	[2.0, 3.0],
		ERA_RP:	[1.0, 2.0],
		WHIP:	[1.0, 1.3],
		'K/BB':	[2.5, 3],
		'K/9':	[6, 8]
	};

	const STATS_TOTAL = { // low, high (per AB=550)
	  AB: 550.0,
	  RANK:	[100, 250],
		R: 		[75, 90],
		H: 		[140, 160],
		HR: 	[25, 35],
		RBI: 	[80, 100],
		SB: 	[20, 30],
		FPCT: [0.97, 0.99],
		AVG: 	[0.3, 0.32],
		OBP: 	[0.35, 0.4],
		SLG: 	[0.45, 0.53],
		IP: 	[5, 6],
		W: 		[1, 1],
		SV: 	[1, 1],
		HLD: 	[1, 1],
		K: 		[4, 6],
		GIDP:	[1, 2],
		ERA:	[2.5, 3.5],
		WHIP:	[1.0, 1.3],
		'K/BB':	[2.5, 3],
		'K/9':	[6, 8]
	};

	const A_CLASS_BUTTON = 'yspnavButton';

	var UPDATE_TIMER = null;
	const UPDATE_ENGINE = 'yahoo';
	const UPDATE_INTERVAL = 150; // sec

	const USE_CUSTOM_STAT_TABLE = false;

	// =====================================================================================================

	function onClickAutoRefreshButton(e)	{
		//createUpdateIcons();

		if(UPDATE_TIMER){
			clearInterval(UPDATE_TIMER);
			UPDATE_TIMER = null;
			this.innerHTML='AutoUpdate';
		}else{
			var s = prompt('Specify boxscore site and update interval(sec):', UPDATE_ENGINE +','+ UPDATE_INTERVAL).split(',');
			UPDATE_ENGINE = s[0].toLowerCase();
			UPDATE_INTERVAL = parseInt(s[1]);

			UPDATE_TIMER = setInterval(getScorebox, UPDATE_INTERVAL*1000);
			this.innerHTML='Stop';
			getScorebox();
		}
	}

	function createPlayerStatIcons()	{
		$x("//a[@class='name'] | //td[@class='player']/a[@target='sports']").each(function(a){
			if(a.nextSibling){
				try{
					if(a.nextSibling.id.indexOf('player_')==0)	return;
				}catch(e){_log(e);}
			}
			var playerName = escape(a.innerHTML).latinUnicodeToAscii();
			_log(a.innerHTML);
			_log(playerName);
			// _log(escape(playerName));
			// _log(encodeURI(playerName));
			// _log(encodeURIComponent(playerName));
			var p_href = a.href;
			var playerId = p_href.substring(p_href.lastIndexOf('/')+1, p_href.length);
			if(isNaN(parseInt(playerId)))	return;
			a.target = playerName;
			_insertAfter(_domCreateImgButton({
				id: 'player_'+playerId,
				url: YFB.URL_PLAYER_SEARCH.replace('<playerName>', playerName),
				img: ICON_MAN_GREEN,
				target: 'player_'+playerId,
				hint: 'show player\'s full stats'
			}), a);
		});
	}

	function createTeamStatIcons()	{
		$x("//td[@class='team']/a").each(function(a){
			var teamName = a.innerHTML;
			var p_href = a.href;
			var teamId = p_href.substring(p_href.lastIndexOf('/')+1, p_href.length);
			a.target = teamName;
			_insertAfter(_domCreateImgButton({
				id: 'team_'+teamId,
				url: YFB.URL_BATTER_TOTAL_TEAM.replace('<teamId>', teamId),
				img: ICON_MAN_GREEN,
				target: teamName + '_stats',
				hint: 'show team\'s full stats'
			}), a);
		});


	}

	function setYspNavItem(li, text, url){
		var a = li.firstChild;
		a.innerHTML = text;
		a.href = url;
	}

	function createNavButton(info) {//className, text, url, target, func
		var yspnav = $('yspnav');
		if(!yspnav)	return;

		var lis = $x("//div[@id='yspnav']//li[contains(@class,'last')]");
		var li = lis[lis.length-1];	// StatTracker

		var newLi = _ce('li');
		newLi.innerHTML = '<a>'+info.text+'</a>';
		if(info.className) newLi.className = info.className;

		var a = newLi.firstChild;
		a.className = A_CLASS_BUTTON;
		if(info.url)		a.href = info.url;
		if(info.target) a.target = info.target;
		if(info.func)		a.addEventListener('click', info.func, true);

		_insert(newLi, li);

		return newLi;
	}

	function createNavItem(text, url)	{
		var li = $x0("//div[@id='yspnav']//li[2]");
		var li_new = li.cloneNode(true);
		li_new.className = '';
		setYspNavItem(li_new, text, url);
		_insertAfter(li_new, li);
		return li_new;
	}

	function changeYspNav()	{
		// hide some items
		$x("//div[@id='yspnav']//li/a").each(function(a){
			if(a.innerHTML=='Tools' ||
					a.innerHTML=='Draft Central' ||
					a.innerHTML.indexOf('Expert Advice')>0 ||
					a.innerHTML.indexOf('StatTracker')>0
				){
				//_del(a.parentNode);
				_addClass(a.parentNode, 'aplHidden');
			}
		});

		// yspnav create link
		var li = $x0("//div[@id='yspnav']//a[contains(@href,'/players')]/parent::*");
		setYspNavItem(li, 'Batter', YFB.URL_BATTER_TOTAL);

		var li_new = createNavItem('Pitcher', YFB.URL_PITCHER_TOTAL);
		_insertAfter(li_new, li);

		createNavItem('Standing', YFB.URL_STANDINGS);

		if(TEAM_ID && !isNaN(TEAM_ID)){
			createNavItem('Watch', YFB.URL_WATCH_TOTAL);
		}
/*
		_insertAfter(createNavItem('Standing', YFB.URL_STANDINGS),
									li);

    if(TEAM_ID && !isNaN(TEAM_ID)){
			_insertAfter(createNavItem('Watch', YFB.URL_WATCH_TOTAL),
										li);
		}

		_insertAfter(createNavItem('Pitcher', YFB.URL_PITCHER_TOTAL),
									li);
*/

		// yspnav open in new tab
		$x("//div[@id='yspnav']//a[@href]").each(function(a,i){
			a.href += (a.href.indexOf('?')>0? '&':'?') + 'navitem=' + i;
			a.target = a.href;
		});

		// check which is selected
		var navitem = parseInt(THIS_URL_PARAMS.navitem);
		$x("//div[@id='yspnav']//li").each(function(li,i){
			if(i==navitem)
				_addClass(li, 'selected');
			else
				_delClass(li, 'selected');
		});

		// create Pictures button
		createNavButton({
			className: 'last',
			text: 'Pictures',
			func: onClickPicturesButton
		});

	}

	function onClickPicturesButton(e){
		//$x("//a[@class='name']").each(function(a){
		$x("//a[contains(@href, '/players/')]").each(function(a){
			try{
				var playerUrl = a.href;
				var playerId = playerUrl.substring(playerUrl.lastIndexOf('/')+1, playerUrl.length);
				if(isNaN(playerId))	return;

				var picId = 'pic_' + playerId;
				var pic = $(picId);
				if(pic){
					_del(pic);
				}else{
					pic = _ce('img');
					pic.src = YFB.URL_ESPN_PLAYER_PICTURE.replace('<playerId>', playerId);
					pic.id = picId;
					_insert(pic, a);
				}
			}catch(ex){
				_err(ex);
			}
		});
	}

	function common()	{
		createTeamStatIcons();
		createPlayerStatIcons();
		changeYspNav();
	}

	function hilitPlayerStatsDaily(rankItems, playerTds){
		var d = 0;
		var f = 0.0;
		var s = '';
		var s2 = '';
		var ip = 0.0;

		try{
			rankItems.each(function(rankItem, i){
				var playerTd = playerTds[i];
				if(playerTd.innerHTML.indexOf('-')>=0)	return;
				switch(rankItem){
					case 'O-Rank':
					case 'Rank':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d<=STATS_DAILY.RANK[0])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d>STATS_DAILY.RANK[1])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}

					// batter -------------------------------------------------
					case 'H/AB':{ // AVG
						s = playerTd.innerHTML;
						if(isNaN(eval(s))){
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						}else{
							f = parseFloat(eval(s));
							if(f>=STATS_DAILY.AVG[1])
								playerTd.innerHTML = _htmlAddColor(s, 'blue');
							else if(f<STATS_DAILY.AVG[0])
								playerTd.innerHTML = _htmlAddColor(s, 'red');
						}
						break;
					}
					case 'R':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=STATS_DAILY.R[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.R[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'H':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=STATS_DAILY.H[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.H[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HR':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=STATS_DAILY.HR[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.HR[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'RBI':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=STATS_DAILY.RBI[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.RBI[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SB':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=STATS_DAILY.SB[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.SB[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'FPCT':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_DAILY.FPCT[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY.FPCT[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'AVG':{
						s = playerTd.innerHTML;
						f = s.indexOf(0)=='.'? parseFloat('0'+s) : parseFloat(s);
						if(f>=STATS_DAILY.AVG[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY.AVG[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'OBP':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_DAILY.OBP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY.OBP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SLG':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_DAILY.SLG[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY.SLG[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					// pitcher -------------------------------------------------
					case 'IP':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						ip = d;
						// if(d>=STATS_DAILY.IP[1])
							// playerTd.innerHTML = _htmlAddColor(s, 'blue');
						// else if(d<STATS_DAILY.IP[0])
							// playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'W':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_DAILY.W[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.W[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SV':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_DAILY.SV[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.SV[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HLD':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_DAILY.HLD[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.HLD[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_DAILY.K[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.K[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'GIDP':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_DAILY.GIDP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_DAILY.GIDP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'ERA':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(ip>=4){//sp
							if(f<=STATS_DAILY.ERA_SP[0])
								playerTd.innerHTML = _htmlAddColor(s, 'blue');
							else if(f>STATS_DAILY.ERA_SP[1])
								playerTd.innerHTML = _htmlAddColor(s, 'red');
						}else{//rp
							if(f<=STATS_DAILY.ERA_RP[0])
								playerTd.innerHTML = _htmlAddColor(s, 'blue');
							else if(f>STATS_DAILY.ERA_RP[1])
								playerTd.innerHTML = _htmlAddColor(s, 'red');
						}
						break;
					}
					case 'WHIP':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f<=STATS_DAILY.WHIP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f>STATS_DAILY.WHIP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/BB':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(s=='INF' || f>=STATS_DAILY['K/BB'][1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY['K/BB'][0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/9':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(f>=STATS_DAILY['K/9'][1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_DAILY['K/9'][0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
				}
			});
		}catch(e){
			_err(e);
		}
	}

	function floatToInt(f)	{
		var s=f.toString().split('.');
		if(s.length==2){
			var i = parseInt(s[1].charAt(0));
			return parseInt(s[0]) + (i>=5? 1:0);
		}else{
			return parseInt(f);
		}
	}

	function hilitPlayerStats(rankItems, playerTds){
		var d = 0;
		var f = 0.0;
		var s = '';
		var s2 = '';
		var ab = 0.0;

		try{
			rankItems.each(function(rankItem, i){
				var playerTd = playerTds[i];
				if(playerTd.innerHTML.indexOf('-')>=0)	return;
				switch(rankItem){
					case 'O-Rank':
					case 'Rank':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d<=STATS_TOTAL.RANK[0])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d>STATS_TOTAL.RANK[1])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}

					// batter -------------------------------------------------
					case 'H/AB':{ // AVG
						s = playerTd.innerHTML;
						if(s!='-/-'){
							ab = parseFloat(playerTd.innerHTML.split('/')[1]);
							f = parseFloat(eval(s));
							if(f>=STATS_TOTAL.AVG[1])
								playerTd.innerHTML = _htmlAddColor(s, 'blue');
							else if(f<STATS_TOTAL.AVG[0])
								playerTd.innerHTML = _htmlAddColor(s, 'red');
						}
						break;
					}
					case 'R':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=floatToInt(STATS_TOTAL.R[1]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<floatToInt(STATS_TOTAL.R[0]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'H':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=floatToInt(STATS_TOTAL.H[1]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<floatToInt(STATS_TOTAL.H[0]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HR':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=floatToInt(STATS_TOTAL.HR[1]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<floatToInt(STATS_TOTAL.HR[0]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'RBI':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=floatToInt(STATS_TOTAL.RBI[1]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<floatToInt(STATS_TOTAL.RBI[0]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SB':{
						s = playerTd.innerHTML;
						d = parseInt(s);
						if(d>=floatToInt(STATS_TOTAL.SB[1]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<floatToInt(STATS_TOTAL.SB[0]*ab/STATS_TOTAL.AB))
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'FPCT':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_TOTAL.FPCT[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL.FPCT[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'AVG':{
						s = playerTd.innerHTML;
						f = s.indexOf(0)=='.'? parseFloat('0'+s) : parseFloat(s);
						if(f>=STATS_TOTAL.AVG[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL.AVG[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'OBP':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_TOTAL.OBP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL.OBP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SLG':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f>=STATS_TOTAL.SLG[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL.SLG[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					// pitcher -------------------------------------------------
					case 'IP':{
						s = playerTd.innerHTML;
//						_log(s);
						d = parseFloat(s);
						if(d>=STATS_TOTAL.IP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.IP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'W':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_TOTAL.W[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.W[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SV':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_TOTAL.SV[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.SV[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_TOTAL.K[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.K[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'GIDP':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_TOTAL.GIDP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.GIDP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HLD':{
						s = playerTd.innerHTML;
						d = parseFloat(s);
						if(d>=STATS_TOTAL.HLD[1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(d<STATS_TOTAL.HLD[0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'ERA':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(f<=STATS_TOTAL.ERA[0])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f>STATS_TOTAL.ERA[1])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'WHIP':{
						s = playerTd.innerHTML;
						f = parseFloat('0'+s);
						if(f<=STATS_TOTAL.WHIP[0])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f>STATS_TOTAL.WHIP[1])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/BB':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(f>=STATS_TOTAL['K/BB'][1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL['K/BB'][0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/9':{
						s = playerTd.innerHTML;
						f = parseFloat(s);
						if(f>=STATS_TOTAL['K/9'][1])
							playerTd.innerHTML = _htmlAddColor(s, 'blue');
						else if(f<STATS_TOTAL['K/9'][0])
							playerTd.innerHTML = _htmlAddColor(s, 'red');
						break;
					}
				}
			});
		}catch(e){
			_err(e);
		}
	}


	function hilitPlayerStats_old(rankItems, playerTds){
		var d = 0;
		var f = 0.0;
		var s = '';
		var s2 = '';

		try{
			for(var i=0; i<rankItems.length; i++){
				switch(rankItems[i]){
					case 'O-Rank':
					case 'Rank':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d<=100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d>250)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}

					// batter -------------------------------------------------
					case 'H/AB':{
						// H
						s = playerTds[i].innerHTML.split('/')[0];
						s2 = playerTds[i].innerHTML.split('/')[1];
						d = parseInt(s);
						if(d>=150)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						else
							playerTds[i].innerHTML = s;
						// AB
						d = parseInt(s2);
//						_log('AB='+d);
						if(d>=550)
							playerTds[i].innerHTML += '/' + _htmlAddColor(s2, 'blue');
						else if(d<400)
							playerTds[i].innerHTML += '/' + _htmlAddColor(s2, 'red');
						else
							playerTds[i].innerHTML += '/' + s2;
						break;
					}
					case 'R':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d>=100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<80)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'H':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d>=150)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HR':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d>=30)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<20)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'RBI':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d>=100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<80)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SB':{
						s = playerTds[i].innerHTML;
						d = parseInt(s);
						if(d>=30)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<15)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'FPCT':{
						s = playerTds[i].innerHTML;
						f = parseFloat('0'+s);
						if(f>=0.99)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<0.97)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'AVG':{
						s = playerTds[i].innerHTML;
						f = s.indexOf(0)=='.'? parseFloat('0'+s) : parseFloat(s);
						if(f>=0.3)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<0.27)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'OBP':{
						s = playerTds[i].innerHTML;
						f = parseFloat('0'+s);
						if(f>=0.4)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<0.35)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SLG':{
						s = playerTds[i].innerHTML;
						f = parseFloat('0'+s);
						if(f>=0.53)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<0.45)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					// pitcher -------------------------------------------------
					case 'IP':{
						s = playerTds[i].innerHTML;
//						_log(s);
						d = parseFloat(s);
						if(d>=200)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<150)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'W':{
						s = playerTds[i].innerHTML;
						d = parseFloat(s);
						if(d>=15)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<10)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'SV':{
						s = playerTds[i].innerHTML;
						d = parseFloat(s);
						if(d>=35)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<15)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K':{
						s = playerTds[i].innerHTML;
						d = parseFloat(s);
						if(d>=150)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<100)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'GIDP':{
						s = playerTds[i].innerHTML;
						d = parseFloat(s);
						if(d>=25)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<15)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'HLD':{
						s = playerTds[i].innerHTML;
						d = parseFloat(s);
						if(d>=20)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(d<15)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'ERA':{
						s = playerTds[i].innerHTML;
						f = parseFloat(s);
						if(f<=2.5)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f>3.5)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'WHIP':{
						s = playerTds[i].innerHTML;
						f = parseFloat('0'+s);
						if(f<=1.0)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f>1.3)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/BB':{
						s = playerTds[i].innerHTML;
						f = parseFloat(s);
						if(f>=4)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<3)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
					case 'K/9':{
						s = playerTds[i].innerHTML;
						f = parseFloat(s);
						if(f>=8.5)
							playerTds[i].innerHTML = _htmlAddColor(s, 'blue');
						else if(f<7)
							playerTds[i].innerHTML = _htmlAddColor(s, 'red');
						break;
					}
				}
			}
		}catch(e){
			_err(e);
		}
	}

	function hilitStats(daily)	{
		// check how many statTable there
		$x("//table[contains(@id,'statTable')]").each(function(table){
			_log('table='+table.id);
			// get rank items
			var rankItems = [];
			$x("//table[@id='"+table.id+"']//th[contains(@class, 'stat')]//a[contains(@href, '&sort=')]").each(function(a){
				_log(a.innerHTML);
				rankItems.push(a.innerHTML);
			});

			if(rankItems.length==0){
				$x("//table[@id='"+table.id+"']//th[contains(@class, 'stat')]/div").each(function(d){
					_log(d.innerHTML);
					rankItems.push(d.innerHTML);
				});
			}

			if(rankItems.length==0){
				$x("//table[@id='"+table.id+"']//th[contains(@class, 'stat')]").each(function(th){
					_log(th.innerHTML);
					rankItems.push(th.innerHTML);
				});
			}

			// process each player
			$x("//table[@id='"+table.id+"']/tbody/tr").each(function(tr){
				if(!tr.id){
					tr.id = 'playerTr_xxx';
					var a = $x0("//tr[@id='"+tr.id+"']//a[contains(@id, 'player_')]");
					if(!a) return;
					tr.id = 'playerTr_'+a.id.split('_')[1];
				}
				var playerTds = $x("//tr[@id='"+tr.id+"']/td[contains(@class, 'stat')]");
				if(rankItems.length != playerTds.length){
					_log('rankItems.length != playerTds.length');
					_log(rankItems.length);
					_log(playerTds.length);
					return;
				}
				if(daily)
					hilitPlayerStatsDaily(rankItems, playerTds);
				else
					hilitPlayerStats(rankItems, playerTds);
			});

		});
	}

	function benchPlayers()	{
		$x("//td[contains(@class, 'pos')]").each(function(td){
			if(td.innerHTML == 'BN' || td.innerHTML == 'DL'){
				_addClass(td.parentNode, 'bench');
			}
		});
	}

	function genPlayerFullStat()	{
		// find the player's name
		var playerName="";
		var playerUrl="";

		var as = $x("//a[@class='name']");

		// If not found, search last name
		if(as.length==0){
			var name = THIS_URL_PARAMS.search.replace('%20',' ').split(' ');
			if(name.length>=2){
				window.location.href = YFB.URL_PLAYER_SEARCH.replace('<playerName>', name[1].latinUnicodeToAscii());
			}
			return;
		}

		if(as.length > 1) {
			hilitStats();
			return;
		}

		// 1 player
		var a = as[0];
		playerName = THIS_URL_PARAMS.search;
		_htmlSetTitle(playerName);
		playerUrl = a.href;
		var playerId = playerUrl.substring(playerUrl.lastIndexOf('/')+1, playerUrl.length);

		_ajax(
			YFB.URL_PLAYER_SEARCH_2006.replace('<playerName>', playerName),
			function(r) {
				processPlayerStats2006(_getAjaxHtmlBody(r));
				hilitStats();
			}
		);

		_ajax(
			YFB.URL_PLAYER_GAMELOG.replace('<playerId>', playerId),
			function(r) {
				processPlayerGamelog(_getAjaxHtmlBody(r));
			}
		);
	}

	function processPlayerStats2006(html){
		var tbody = $x0("//table[@id='statTable0']/tbody");
		if(!tbody) return;

		var div = _domInsertHddenHtml(html);
		try{
			$x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//table[@id='statTable0']/tbody/tr").each(function(tr){
				tr.firstChild.innerHTML = '2006 Total';
				_add(tbody, tr);
			});
		}finally{ div.innerHTML = '';	}
	}

	function processPlayerGamelog(html){
		var statTable0 = $x0("//table[@id='statTable0']");
		if(!statTable0) return;

		var div = _domInsertHddenHtml(html);
		try{
			var table = $x0("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//tr[@class='yspsctbg']/parent::*/parent::*");
			if(!table)		return;

			table.id = 'statTable1';
			table.className = 'teamtable';
			$x0("//table[@id='statTable1']//tr[@class='yspsctbg']").className = 'headerRow0';
			$x0("//table[@id='statTable1']//tr[@class='ysptblthbody1']").className = 'headerRow1';
			$x("//table[@id='statTable1']//tr[contains(@class,'ysprow')]").each(function(tr){
				tr.className = (tr.className=='ysprow1'? 'odd':'even');
			});
			_insertAfter(table, statTable0);

		}finally{ div.innerHTML = '';	}
	}

	function processPlayerInfo(html, playerName){
		_log('processPlayerInfo(): '+playerName);

		var statTable0 = $x0("//table[@id='statTable0']");

		var div = _domInsertHddenHtml(html);
		try{
			var statTable1 = $x0("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//table[@id='statTable0']");
			if(!statTable1)		return;

			if(statTable0){
				var tbody = $x0("//table[@id='statTable0']/tbody");

				statTable1.id = 'statTable1';
				$x("//table[@id='statTable1']/tbody/tr").each(function(tr){
					_add(tbody, tr);
				});
			}else{
				var a = $x0("//a[@id='maincontent']");
				if(!a) return;
				_insertAfter(statTable1, a);
			}
		}finally{ div.innerHTML = '';	}

	}

	function searchMultiPlayers()	{
		var players = THIS_URL_PARAMS.search;
		if(players.indexOf(',')<0)	return false;

		var pList = players.split(',');

		pList.each(function(playerName){
			_ajax(
				YFB.URL_PLAYER_SEARCH.replace('<playerName>', playerName),
				function(r, userData) {
					processPlayerInfo(_getAjaxHtmlBody(r), userData.playerName);
				},
				{ playerName: playerName }
			);
		});

	}

	function createGameLinkIcons()	{
		$x("//td[@class='gametime']/a").each(function(a){
			a.href = a.href.replace('recap', 'boxscore');
			a.target = a.href;
			var espnGameUrl = a.href.replace('yahoo', 'espn.go').replace('gid', 'gameId');
			_add(a.parentNode, _domCreateImgButton({
				id: '',
				url: espnGameUrl,
				img: ICON_ESPN,
				target: espnGameUrl,
				hint: 'ESPN score box'
			}));

		});

	}

	function processTeamStats(html)	{
		var statTable0 = $x0("//table[@id='statTable0']");

		var div = _domInsertHddenHtml(html);
		try{
			var statTable1 = $x0("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//table[@id='statTable0']");
			if(!statTable1)		return;

			statTable1.id = 'statTable1';
			_insertAfter(statTable1, statTable0);

		}finally{ div.innerHTML = '';	}
	}

	function createStatTable_old(){ // todo: some problems here
		if(USE_CUSTOM_STAT_TABLE) return;

		// batter
		var stats = ['H/AB', 'R', 'H', 'HR', 'RBI', 'SB', 'AVG', 'OBP'];
		var th_last = $x0("//table[@id='statTable0']//tr[@class='headerRow1']/th[contains(@class, 'stat')]");

		stats.each(function(stat){
			var th = th_last.cloneNode(true);
			th.className = 'stat';
			th.innerHTML = stat;
			_insert(th, th_last);
		});
		_del(th_last);

		$x("//table[@id='statTable0']//td[contains(@class,'statspromo')]").each(function(td_last){
			stats.each(function(stat){
				var td = td_last.cloneNode(true);
				td.className = 'stat';
				td.innerHTML = '-';
				_insert(td, td_last);
			});
			_del(td_last);
		});

		// pitcher
		stats = ['IP', 'W', 'SV', 'HLD', 'K', 'ERA', 'WHIP', 'K/BB', 'K/9'];
		var th_last = $x0("//table[@id='statTable1']//tr[@class='headerRow1']/th[contains(@class, 'stat')]");

		stats.each(function(stat){
			var th = th_last.cloneNode(true);
			th.className = 'stat';
			th.innerHTML = stat;
			_insert(th, th_last);
		});
		_del(th_last);

		$x("//table[@id='statTable1']//td[contains(@class,'statspromo')]").each(function(td_last){
			stats.each(function(stat){
				var td = td_last.cloneNode(true);
				td.className = 'stat';
				td.innerHTML = '-';
				_insert(td, td_last);
			});
			_del(td_last);
		});

		USE_CUSTOM_STAT_TABLE = true;
	}

	function createStatTable(){ // todo: some problems here
		if(USE_CUSTOM_STAT_TABLE) return;

		// remove all 'stat' except 'stat last'
		$x("//th[contains(@class, 'stat')] | //td[contains(@class, 'stat')]").each(function(cell){
			if(!_hasClass(cell, 'last')) _del(cell);
		});

		// batter
		var stats = ['H/AB', 'R', 'H', 'HR', 'RBI', 'SB', 'AVG', 'OBP'];
		var th_last = $x0("//table[@id='statTable0']//tr[@class='headerRow1']/th[contains(@class, 'stat')]");

		stats.each(function(stat){
			var th = th_last.cloneNode(true);
			th.className = 'stat';
			th.innerHTML = stat;
			_insert(th, th_last);
		});
		_del(th_last);

		$x("//table[@id='statTable0']//td[contains(@class,'stat')]").each(function(td_last){
			stats.each(function(stat){
				var td = td_last.cloneNode(true);
				td.className = 'stat';
				td.innerHTML = '-';
				_insert(td, td_last);
			});
			_del(td_last);
		});

		// pitcher
		stats = ['IP', 'W', 'SV', 'HLD', 'K', 'ERA', 'WHIP', 'K/BB', 'K/9'];
		var th_last = $x0("//table[@id='statTable1']//tr[@class='headerRow1']/th[contains(@class, 'stat')]");

		stats.each(function(stat){
			var th = th_last.cloneNode(true);
			th.className = 'stat';
			th.innerHTML = stat;
			_insert(th, th_last);
		});
		_del(th_last);

		$x("//table[@id='statTable1']//td[contains(@class,'stat')]").each(function(td_last){
			stats.each(function(stat){
				var td = td_last.cloneNode(true);
				td.className = 'stat';
				td.innerHTML = '-';
				_insert(td, td_last);
			});
			_del(td_last);
		});

		USE_CUSTOM_STAT_TABLE = true;
	}

	function getHRorSB(type, playerName) {
		var nodes = $x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//td[@class='yspscores' and contains(.,'" + type + "') and contains(.,'" + playerName + "')]", document);
		var j = nodes.length;
		var numStat = 0;

		if (j) {
			var statLine = nodes[j-1].textContent; //nodes.snapshotItem(j - 1).textContent;
			//does the name appear in the catcher field?
			statLine = statLine.replace(/\([^\)].+?\)/gi,'');
			if (statLine.indexOf(playerName) > -1) {
				var re = new RegExp(".*(" + playerName + " *\\d?).+", 'gi');
				statLine = statLine.replace(re, "$1");
				statLine = statLine.replace(/[^\d]+/, '');
				numStat = (statLine == '') ? 1 : statLine;
			}
		}
		return numStat;
	}

	function processScorebox(html, players){
		_log('processScorebox(): ' + players.length);

		var div = _domInsertHddenHtml(html);
		try{
			players.each(function(player){
				var tr = player.tr;
				var type = player.type;
				var playerId = tr.id.split('_')[1];

				var as = $x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//tr[contains(@class, 'ysprow')]//a[contains(@href, '/players/"+playerId+"')]");
				if(as.length==0) return;

				var a = as[as.length-1];

				var pTr = a.parentNode.parentNode;
				var pTds = _gt(pTr, 'td');
				var tds = $x("//tr[@id='"+tr.id+"']/td[contains(@class, 'stat')]");

				switch(type){
					case 0: {	// batter
						var batter = a.innerHTML.replace('.', '');
						var i, ab, r, h, rbi, bb, obp, hr, sb, avg;
						ab 	= pTds[1].innerHTML * 1;
						r 	= pTds[2].innerHTML * 1;
						h 	= pTds[3].innerHTML * 1;
						rbi = pTds[4].innerHTML * 1;
						bb 	= pTds[5].innerHTML * 1;
						avg = (isNaN(h/ab)? 0: (h/ab)).toFloatString();
						obp = (isNaN((h+bb)/(ab+bb))? 0: ((h+bb)/(ab+bb))).toFloatString();
						hr = getHRorSB('HR', batter, html);
						sb = getHRorSB('SB', batter, html);

						i=0;
						tds[i++].innerHTML = h + '/' + ab;
						tds[i++].innerHTML = r;
						tds[i++].innerHTML = h;
						tds[i++].innerHTML = hr;
						tds[i++].innerHTML = rbi;
						tds[i++].innerHTML = sb;
						tds[i++].innerHTML = avg;
						tds[i++].innerHTML = obp;
					} break;

					case 1: {	// pitcher
						var pitcherInfo = a.parentNode.innerHTML;
						var i, ip, h, er, bb, w, sv, hld, k, era, whip, kbb, k9;
						ip 	= parseFloat(pTds[1].innerHTML);
						h 	= pTds[2].innerHTML * 1;
						er 	= pTds[4].innerHTML * 1;
						bb 	= pTds[5].innerHTML * 1;
						k 	= pTds[6].innerHTML * 1;
						era = 9*er/ip;
						whip = (h+bb)/ip;
						kbb = (k==0? 0: (bb==0? 'INF': k/bb));
						k9 = 9*k/ip;
						w = (pitcherInfo.indexOf("(W") > -1) ? 1: 0;
						sv = (pitcherInfo.indexOf("(S") > -1) ? '1' : '0';
						hld = (pitcherInfo.indexOf("(H") > -1) ? '1' : '0';

						i=0;
						tds[i++].innerHTML = ip.toFixed(1);
						tds[i++].innerHTML = w;
						tds[i++].innerHTML = sv;
						tds[i++].innerHTML = hld;
						tds[i++].innerHTML = k;
						tds[i++].innerHTML = era.toFixed(2);
						tds[i++].innerHTML = whip.toFixed(2);
						tds[i++].innerHTML = (kbb=='INF'? kbb: kbb.toFixed(2));
						tds[i++].innerHTML = k9.toFixed(2);
					} break;
				}//switch
			});
		}finally{ div.innerHTML = '';	}
	}

	var SCOREBOX_CNT = 0;
	function getScorebox(){
		createStatTable();

		var games = [];
		for(var i=0; i<=1; i++){	// 0: batter; 1: pitcher
			$x("//table[@id='statTable"+i+"']//a[contains(@id, 'player_')]").each(function(a){
				var tr = a.parentNode.parentNode.parentNode;
				tr.id = 'playerTr_' + a.id.split('_')[1];

				var aa = $x0("//tr[@id='"+tr.id+"']/td[@class='gametime']/a");
				if(!aa) return;

				var url = aa.href.replace('recap?', 'boxscore?');

				// check if same game
				var found=false;
				for(var g=0; g<games.length; g++){
					var game=games[i];
					if(url == game.url){
						found=true;
						game.players.push({
							tr: tr,
							type: i
						});
						break;
					}
				}

				if(!found){
					games.push({
						url: url,
						players: [{
							tr: tr,
							type: i
						}]
					});
				}

			});
		}

		// do it
		SCOREBOX_CNT = games.length;
		games.each(function(game){
			_ajax(
				game.url,
				function(r, userData) {
					processScorebox(_getAjaxHtmlBody(r), userData.players);
					if(--SCOREBOX_CNT==0){
						hilitStats(true);
					}
				},
				{players: game.players}
			);
		});
	}

	function yspteam()	{
		_htmlSetTitle($x0("//div[@id='teaminfo']//em").innerHTML);

		// matchup
		var a=$x0("//a[contains(@href,'matchup?')]");
		if(a){
			createNavItem('Matchup', a.href);
		}

		benchPlayers();
		createGameLinkIcons();
		//alert($x("//table[@id='statTable0']//th[contains(@class, 'stat')]").length);

			createNavButton({
				className: 'last',
				text: 'AutoRefresh',
				func: onClickAutoRefreshButton
			});

			/* create a nav-button with icon */
			var li = createNavButton({
				className: 'last',
				text: 'Refresh',
				func: function(e){	getScorebox();}
			});
			var btn = _domCreateImgButton({
					img: ICON_REFRESH,
					hint: 'refresh boxscore',
					events: [['click', getScorebox]]
			});
			btn.className = 'yspnavButton';
			_replace(btn, li.firstChild);
			/* end: create a nav-button with icon */
/*
		if($x("//table[@id='statTable0']//th[contains(@class, 'stat')]").length<5){
			createStatTable();
		}else{
			hilitStats(true);
		}
*/
		hilitStats(true);

		// create team stats icon
		var em = $x0("//div[@id='teaminfo']//em");
		_insertAfter(_domCreateImgButton({
			id: em.innerHTML,
			url: YFB.URL_BATTER_TOTAL_TEAM.replace('<teamId>', TEAM_ID),
			img: ICON_MAN_GREEN,
			target: em.innerHTML + '_stats',
			hint: 'show team\'s full stats'
		}), em);

		// datenav
		$x("//div[@id='datenav']//a").each(function(a){
			a.target='_blank';
		});
	}

	function yspplayers(){
		// team players?
		if(!isNaN(parseInt(THIS_URL_PARAMS.status))){
			var teamId = parseInt(THIS_URL_PARAMS.status);
			var sel = $x0("//select[@id='statusselect']");
			_htmlSetTitle(sel.options[sel.selectedIndex].text + ' - players');

			var url = THIS_URL;
			if(THIS_URL_PARAMS.pos){
				if(THIS_URL_PARAMS.pos==='B'){
					url = url.replace('pos=B', 'pos=P');
				}else{
					url = url.replace('pos=P', 'pos=B');
				}
				_ajax(
					url,
					function(r) {
						processTeamStats(_getAjaxHtmlBody(r));
						createPlayerStatIcons();
						hilitStats();
					}
				);
			}else{
				window.location = YFB.URL_BATTER_TOTAL_TEAM.replace('<teamId>', teamId);
			}

		}else{
			if(THIS_URL_PARAMS.pos==='B')
				_htmlSetTitle('Batters');
			else if(THIS_URL_PARAMS.pos==='P')
				_htmlSetTitle('Pitchers');
			else
			_htmlSetTitle('Players');
			hilitStats();
		}
	}

	function yspplayersearch()	{
		_htmlSetTitle('Players');

		// search multi players?
		if(searchMultiPlayers())	return;

		genPlayerFullStat();
	}

	function yspplayerswatch()	{
		if(!THIS_URL_PARAMS.sort){
			window.location = YFB.URL_WATCH_TOTAL;
		}

		_htmlSetTitle('WatchList');
		hilitStats();
	}

	function yspstandings(){
		var total = $x("//table[@id='statTable0']/tbody/tr").length;
		var rank = parseInt($x0("//table[@id='statTable0']//tr[contains(@class, 'selected')]/td[contains(@class, 'rank')]").innerHTML);
		_htmlSetTitle('Standing ' + rank + '/' + total);
	}

	function yspleaguehome(){
		//_htmlSetTitle($x0("//div[@id='leaguehome-title']/h1").innerHTML);
		_htmlSetTitle('ID# '+LEAGUE_ID);
	}

	function yspmatchup(){
		var tds = $x("//div[@id='boxscore']//td[contains(@class, 'pts')]");
		_htmlSetTitle('Matchup '+tds[0].innerHTML + ':' + tds[1].innerHTML);
	}

	// =====================================================================================================

	common();
	switch(document.body.id)	{
		case 'yspleaguehome':
			yspleaguehome();
			break;
		case 'yspplayers':
			yspplayers();
			break;
		case 'yspteam':
			yspteam();
			break;
		case 'yspplayersearch':
			yspplayersearch();
			break;
		case 'yspplayerswatch':
			yspplayerswatch();
			break;
		case 'yspstandings':
			yspstandings();
			break;
		case 'yspmatchup':
			yspmatchup();
			break;
	}

}

// =============================================================================
// global functions
// =============================================================================
String.prototype.latinUnicodeToAscii = function(){
	// http://htmlhelp.com/reference/html40/entities/latin1.html
	var UNICODE_ASCII=[
		['%20', ' '],
		['%C0', 'A'],
		['%C1', 'A'],
		['%C2', 'A'],
		['%C3', 'A'],
		['%C4', 'A'],
		['%C5', 'A'],
		['%C6', 'A'],
		['%C8', 'E'],
		['%C9', 'E'],
		['%CA', 'E'],
		['%CB', 'E'],
		['%CC', 'I'],
		['%CD', 'I'],
		['%CE', 'I'],
		['%CF', 'I'],
		['%D1', 'N'],
		['%D2', 'O'],
		['%D3', 'O'],
		['%D4', 'O'],
		['%D5', 'O'],
		['%D6', 'O'],
		['%D9', 'U'],
		['%DA', 'U'],
		['%DB', 'U'],
		['%DC', 'U'],
		['%DD', 'Y'],
		['%E0', 'a'],
		['%E1', 'a'],
		['%E2', 'a'],
		['%E3', 'a'],
		['%E4', 'a'],
		['%E5', 'a'],
		['%E8', 'e'],
		['%E9', 'e'],
		['%EA', 'e'],
		['%EB', 'e'],
		['%EE', 'i'],
		['%ED', 'i'],
		['%EE', 'i'],
		['%EF', 'i'],
		['%F1', 'n'],
		['%F2', 'o'],
		['%F3', 'o'],
		['%F4', 'o'],
		['%F5', 'o'],
		['%F6', 'o'],
		['%F9', 'u'],
		['%FA', 'u'],
		['%FB', 'u'],
		['%FC', 'u'],
		['%FD', 'y'],
		['%FF', 'y']
	];
	var s = this;
	UNICODE_ASCII.each(function(ua){
		var re = new RegExp(ua[0], "g");
		s = s.replace(re, ua[1]);
	});
	return s;
};


/*
 input: 1, 			return: 1.000
 input: 1.2345, return: 1.235
 input: 0.23, 	return: .230
*/
Number.prototype.toFloatString = function(digit){
	if(!digit) digit=3;

	var f = parseFloat(this);
	var s = f.toFixed(digit).toString();

	if(s.indexOf(0)=='0')
		return s.substring(1, s.length);
	else
		return s;
};


String.prototype.toTruncFloat = function(digit){
	if(!digit)		digit=3;
	var s = this;
	if(isNaN(s))	return s;

	var f = parseFloat(s);

	if(s.search(/\./)<0)	s += '.0';
	s = s.replace(/^0./, '.');
	if(s.length > 4){
		var i=s.search(/\./);
		s = s.substring(0, i+((f>=1)?3:4));	// 3 digits after .
	}

	while(s.length<digit+1){
		s += '0';
	}

	return s;
};

